//
//  PhoneRechargeController.m
//  Terran
//
//  Created by 李勋 on 16/3/6.
//  Copyright © 2016年 yuwubao. All rights reserved.
//

#import "PhoneRechargeController.h"
#import "PhoneRechargeCell.h"
#import <Masonry.h>

//Secret Input View
#import "ZCTradeView.h"

//Logic Model
#import "GetUserAccountInfoEngine.h"
#import "ConvenientPayOrderEngine.h"

#import "ConvenientPayConfirmEngine.h"
#import "VerifyPayPasswordEngine.h"
#import "GetUserDetailInfoEngine.h"

//Utility Model
#import "YuLoginRegisterUtilities.h"

#import "PhoneRechagePayInfoController.h"

//FinishPay

#import "PhoneRechargePayFinishViewController.h"

static NSString *const phoneRechargeCellID = @"phoneRehargeCellID";

@interface PhoneRechargeController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITextFieldDelegate,PhoneRechagePayInfoDelegate,ZCTradeViewDelegate>
{
    UIButton *addressBtn;
}



@property (nonatomic, strong)UIButton *closeBtn;

@property (nonatomic, strong)UICollectionView *itemsCollectionView;

@property (nonatomic, strong)NSArray *itemArray;

@property (nonatomic) BOOL isAllowChoosing;

@property (nonatomic, strong) NSIndexPath *selectedIndexPath;

/**
 *  <#Description#>
 */
@property (nonatomic,strong) GetUserAccountInfoEngine *getUserAccountInfoEngine;

@property (nonatomic,strong) ConvenientPayOrderEngine *convenientPayOrderEngine;

@property (nonatomic,strong) NSDictionary *orderInfo;

//@property (nonatomic,strong) NSString *phone;

/**
 *  <#Description#>
 */
@property (nonatomic,strong)  ConvenientPayConfirmEngine *convenientPayConfirmEngine;

@property (nonatomic, strong) VerifyPayPasswordEngine *verifyPayPasswordEngine;

@property (nonatomic, strong) GetUserDetailInfoEngine *getUserDetailInfoEngine;


@property (nonatomic, strong) NSDictionary *chosenCard;

@property (nonatomic,strong) ZCTradeView *tradeView;


/**
 *  Finish Pay
 */
@end

@implementation PhoneRechargeController
- (GetUserDetailInfoEngine *)getUserDetailInfoEngine
{
    if (!_getUserDetailInfoEngine) {
        _getUserDetailInfoEngine = [[GetUserDetailInfoEngine alloc] init];
    }
    return _getUserDetailInfoEngine;
}

- (ConvenientPayConfirmEngine *)convenientPayConfirmEngine
{
    if (!_convenientPayConfirmEngine) {
        _convenientPayConfirmEngine = [[ConvenientPayConfirmEngine alloc] init];
    }
    return _convenientPayConfirmEngine;
}
- (VerifyPayPasswordEngine *)verifyPayPasswordEngine
{
    if (!_verifyPayPasswordEngine) {
        _verifyPayPasswordEngine = [[VerifyPayPasswordEngine alloc] init];
    }
    return _verifyPayPasswordEngine;
}
/**
 *  获取用户银行卡信息的逻辑模型
 *
 *
 */
- (GetUserAccountInfoEngine *)getUserAccountInfoEngine
{
    if (!_getUserAccountInfoEngine) {
        _getUserAccountInfoEngine = [[GetUserAccountInfoEngine alloc] init];
    }
    return _getUserAccountInfoEngine;
}

- (ConvenientPayOrderEngine *)convenientPayOrderEngine
{
    if (!_convenientPayOrderEngine) {
        _convenientPayOrderEngine = [[ConvenientPayOrderEngine alloc] init];
    }
    return _convenientPayOrderEngine;
}


-(NSArray *)itemArray
{
    if (!_itemArray) {
        _itemArray = @[@{@"title":@"30元\n售价29.87",@"value":@"30"},@{@"title":@"50元\n售价49.87",@"value":@"50"},
                       @{@"title":@"100元\n售价99.87",@"value":@"100"},@{@"title":@"200元\n售价199.87",@"value":@"200"},@{@"title":@"300元\n售价299.87",@"value":@"300"},@{@"title":@"500元\n售价499.87",@"value":@"500"}];
    }
    return _itemArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /**
     *  设置Tap手势，收起键盘
     */
    [self setupTapGesture];
   
}

-(void)setupUI
{
    self.title = @"话费充值";
    
    self.isAllowChoosing = NO;
    
    [self setupNavBackButton];
    
    self.view.backgroundColor = UIColorFromRGBA(kTableViewSplitLineColor, 1.f);
    self.phoneField.backgroundColor = [UIColor whiteColor];
    self.phoneField.font = [UIFont fontWithName:FONT_NAME size:14.f];
    self.phoneField.textColor = UIColorFromRGBA(kMainTextGrayColor, 1);
    [self.phoneField addTarget:self action:@selector(changeCollectionViewBgColor:) forControlEvents:UIControlEventEditingChanged];
    self.phoneField.delegate = self;
    self.phoneField.leftViewMode = UITextFieldViewModeAlways;
    
    UIView *leftView = [[UIView alloc] init];
    leftView.backgroundColor = [UIColor whiteColor];
    [self.phoneField  addSubview:leftView];
   
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.bottom.equalTo(self.phoneField);
        make.width.equalTo(@20);
    }];
     self.phoneField.leftView = leftView;
    
    
    addressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addressBtn setBackgroundImage:[UIImage imageNamed:@"contacts"] forState:UIControlStateNormal];
    [addressBtn addTarget:self action:@selector(addressBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:addressBtn];
    [addressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bgView.mas_centerY);
        make.right.equalTo(self.bgView).offset(-15);
        make.size.mas_offset(CGSizeMake(17, 19));
    }];

    
    [self setUpCollectionView];
    
}


-(void)setUpCollectionView{
    
    //collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];

    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = [UIColor clearColor];
    self.itemsCollectionView= collectionView;
    [self.view addSubview:self.itemsCollectionView];
    
    
    [self.itemsCollectionView registerNib:[PhoneRechargeCell nib] forCellWithReuseIdentifier:phoneRechargeCellID];

    [self.itemsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneField.mas_bottom).offset(30);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(@220);
    }];
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhoneRechargeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:phoneRechargeCellID forIndexPath:indexPath];
    
      self.selectedIndexPath = indexPath;
   // cell.moneyLabel.text = self.itemArray[indexPath.row] ;
     cell.moneyBtn.tag = indexPath.row;
    
    cell.isAllowChoosing = self.isAllowChoosing;
    NSLog(@"%d %@",cell.moneyBtn.tag, self.itemArray[cell.moneyBtn.tag]);
    [cell.moneyBtn setTitle:self.itemArray[cell.moneyBtn.tag][@"title"] forState:UIControlStateNormal];

//    NSRange range = [string rangeOfString:@"\n"];
//    
//    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:FONT_NAME size:11.0] range:NSMakeRange( range.location+range.length, str.length - (range.location+range.length))];
//    [cell.moneyBtn setAttributedTitle:str forState:UIControlStateNormal];
    
    [cell.moneyBtn addTarget:self action:@selector(tapRechargeButton:) forControlEvents:UIControlEventTouchUpInside];
   
    
    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_WIDTH -60)/ 3 ,(SCREEN_WIDTH -60)/ 3 - 20);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 15, 10, 15);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 6;
}


#pragma mark -<tapRechargeButton>
- (void)tapRechargeButton:(UIButton *)button
{
    NSLog(@"%d",button.tag) ;
    
    /**
     *  获取订单信息，暂时公司号是固定的
     */
    
    NSString *value = self.itemArray[button.tag][@"value"];
    
    NSString *phoneNumber = self.phoneField.text;
    if ([YuLoginRegisterUtilities isMobileNumber:phoneNumber]) {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.convenientPayOrderEngine getPhoneOrderInfoWithID:phoneNumber andType:@"gzTel" andCompany:@"443701060120050" andValue:value];
    }else{
        [self.view makeToast:kMobileNumberInavalid];
    }
    
   

}
#pragma mark - PayInfo Controller Delegate
- (void)okBtnClick:(BOOL)isConfirm withCard:(NSDictionary *)card
{
    self.chosenCard = card;
    
    
    NSString *payAmount = self.orderInfo[@"payAmt"];
    NSString *value = ServerMoneyToShow(payAmount);
    NSString *limit = [YuUserDefaultsUtilities stringWithKey:@"UserPayLimit"];
    if(limit.length && ![limit isEqualToString:@"0"] && [limit integerValue] >= [value integerValue])
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        
        [self.convenientPayConfirmEngine payConvenientOrderwithCard:self.chosenCard];
    }else if(!limit.length){
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserDetailInfoEngine getUserInfo];
    }else{
        self.tradeView =  [[ZCTradeView alloc] initWithTitle:@"请确认支付信息并输入支付密码" andStyle:ZCPresentStyle];
        self.tradeView.delegate = self;
        [self.tradeView showInView:self.view];
    }

}
-(NSString *)finish:(NSString *)pwd confirm:(BOOL)isConfirm
{
    [self.tradeView cancle];
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.verifyPayPasswordEngine verifyPayPassword:pwd];
    
    // self.shadowView.hidden = NO;
    // self.finishView.hidden = NO;
    return pwd;
}
/** 取消按钮点击 */
- (void)cancelBtnClick:(BOOL)isConfirm
{
    NSLog(@"cancel");
}

#pragma mark - TextFieldDelegate
-(void)changeCollectionViewBgColor:(UITextField *)textField
{

   
    if (textField.text.length > 0 ) {
        [addressBtn setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [addressBtn mas_updateConstraints:^(MASConstraintMaker *make) {
          
            make.size.mas_offset(CGSizeMake(15, 15));
        }];
        if (!self.isAllowChoosing ) {
            self.isAllowChoosing = YES;
            [self.itemsCollectionView reloadItemsAtIndexPaths:[self.itemsCollectionView indexPathsForVisibleItems]];
          //  [self.itemsCollectionView reloadData];
        }
        
    }else{
        [addressBtn setBackgroundImage:[UIImage imageNamed:@"contacts"] forState:UIControlStateNormal];
        [addressBtn mas_updateConstraints:^(MASConstraintMaker *make) {

            make.size.mas_offset(CGSizeMake(17, 19));
        }];
        if (self.isAllowChoosing ) {
            self.isAllowChoosing = NO;
            [self.itemsCollectionView reloadItemsAtIndexPaths:[self.itemsCollectionView indexPathsForVisibleItems]];
          //  [self.itemsCollectionView reloadData];
        }
    }

//     [addressBtn addTarget:self action:@selector(addressBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}




-(void)addressBtnClick:(UIButton *)button
{
    if ([[button backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"close"]]) {
        self.phoneField.text = @"";
        [addressBtn setBackgroundImage:[UIImage imageNamed:@"contacts"] forState:UIControlStateNormal];
        [addressBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            
            make.size.mas_offset(CGSizeMake(17, 19));
        }];
        if (self.isAllowChoosing ) {
            self.isAllowChoosing = NO;
            [self.itemsCollectionView reloadItemsAtIndexPaths:[self.itemsCollectionView indexPathsForVisibleItems]];
         //   [self.itemsCollectionView reloadData];
        }
    }
}

#pragma mark - Call back
/**
 *  获取Order的信息
 *
 *  @param notification <#notification description#>
 */
- (void)getCPOrderInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        self.orderInfo = messageDic[@"result"];
        
        NSLog(@"%@",self.orderInfo);
        
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserAccountInfoEngine getAccoutInfo];
        
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}




- (void)getUserAccountInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        if (!messageDic[@"result"][@"cardList"] ) {
            
            UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"您还未绑定银行卡，无法消费，请立即绑定银行卡" andBlock:^(UIAlertAction *action ) {
                ////NSLog(@"%@",action.title);
                if ([action.title isEqualToString:@"好的"]) {
                    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"BankCard" bundle:nil];
                    if ([messageDic[@"result"][@"initPay" ] isEqualToString:@"true"]) {
                        
                        //初次设置支付密码
                        [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"AddCardFirstInputPasswordController"] animated:YES];
                        
                    }else{
                        [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"AddCardCheckPasswordViewController"] animated:YES];
                        
                    }
                }else{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                
            } type:@"confirmAndCancel"];
            [self presentViewController:x animated:YES completion:nil];
            
            
        }else{
            
            NSLog(@"%@",messageDic[@"result"][@"cardList"] );
           UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"ConvenientPay" bundle:nil];
//            
            PhoneRechagePayInfoController *controller =(PhoneRechagePayInfoController *) [storyBoard instantiateViewControllerWithIdentifier:@"PhoneRechagePayInfoController"];
           controller.cardList = messageDic[@"result"][@"cardList"];
            controller.orderInfo = self.orderInfo;
            controller.navigationItem.title = self.title;
            controller.delegate = self;
            controller.convenientPayConfirmEngine = self.convenientPayConfirmEngine;
            controller.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            controller.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            
            
            [self presentViewController:controller animated:YES completion:^{NSLog(@"finish");}];
        }
        
        
        
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}


//验证支付密码回调
- (void)verifyPayPasswordFinish:(NSNotification*) notification
{
    
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        
        [self.convenientPayConfirmEngine payScanOrder:messageDic[@"result"] withCard:self.chosenCard];
    }else{
        [YuNetworkStatusUtilities dismissHUD];
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}//支付订单回调
- (void)payConvenientOrderFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        NSLog(@"%@",messageDic[@"result"])
      //  self.paymentFinishInfo = messageDic[@"result"];
        
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"ConvenientPay" bundle:nil];
        //
        PhoneRechargePayFinishViewController *controller =(PhoneRechargePayFinishViewController *) [storyBoard instantiateViewControllerWithIdentifier:@"PhoneRechargePayFinishViewController"];
        controller.paymentFinishInfo = messageDic[@"result"];
        controller.card = self.chosenCard;
        controller.orderInfo = self.orderInfo;
        [self.navigationController pushViewController:controller animated:YES];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

- (void)getUserInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        NSString *payAmount = self.orderInfo[@"payAmt"];
        NSString *value = ServerMoneyToShow(payAmount);
        NSString *limit = [YuUserDefaultsUtilities stringWithKey:@"UserPayLimit"];
        if(limit.length && ![limit isEqualToString:@"0"] && [limit integerValue] >= [value integerValue])
        {
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            
            [self.convenientPayConfirmEngine payConvenientOrderwithCard:self.chosenCard];
        }else{
            self.tradeView =  [[ZCTradeView alloc] initWithTitle:@"请确认支付信息并输入支付密码" andStyle:ZCPresentStyle];
            self.tradeView.delegate = self;
            [self.tradeView showInView:self.view];
        }
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}
#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserAccountInfoFinish:) name:@"GetUserAccountInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCPOrderInfoFinish:) name:@"GetCPOrderInfoFinish" object:nil];
    
    
    //确认支付后
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifyPayPasswordFinish:) name:@"VerifyPayPasswordFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payConvenientOrderFinish:) name:@"PayConvenientOrderFinish" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoFinish:) name:@"GetUserInfoFinish" object:nil];
    
    if(self.isFromAddCardFinish)
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserAccountInfoEngine getAccoutInfo];
    }
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserAccountInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetCPOrderInfoFinish" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifyPayPasswordFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PayConvenientOrderFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserInfoFinish" object:nil];
}





@end
